package com.woniu.controller;

import com.woniu.util.ConstantUtil;
import com.woniu.util.ResponseEnum;
import com.woniu.util.ResponseUtil;
import com.woniu.vo.CaptchaUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Resource
    private RedisTemplate redisTemplateInit;

    /**
     * 生成验证码
     */
    @GetMapping("/generate")
    public ResponseUtil generateCaptcha() {
        try {
            // 生成验证码
            String[] captchaInfo = CaptchaUtil.generateCaptcha();
            String base64Image = captchaInfo[0];
            String captchaCode = captchaInfo[1];

            // 生成唯一标识
            String captchaKey = UUID.randomUUID().toString();

            // 存储验证码到Redis，有效期5分钟
            redisTemplateInit.opsForValue().set(
                    ConstantUtil.REDIS_CAPTCHA_KEY + captchaKey,
                    captchaCode.toLowerCase(),
                    5,
                    TimeUnit.MINUTES
            );

            // 返回结果
            Map<String, String> result = new HashMap<>();
            result.put("captchaKey", captchaKey);
            result.put("captchaImage", base64Image);

            return ResponseUtil.get(ResponseEnum.SUCCESS, result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.get(ResponseEnum.SYSTEM_ERROR, "获取验证码失败，请重试");
        }
    }
}